package com.example.wangzh.developkit.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.appcompat.widget.AppCompatTextView;
import android.util.AttributeSet;

import com.example.wangzh.developkit.R;

/**
 * Created by USER on 2017/4/18.
 */

public class CountDownView extends AppCompatTextView {
    public interface OnFinishListener {
        void onFinish();
    }

    public interface ReaminTextParser {
        String getRemainText(long minute, long second);
    }

    ReaminTextParser remainTextParser;
    /**
     * 单位毫秒
     */
    String textFormat = "mm:SS";
    String finishText = "已结束";
    long endTime;
    OnFinishListener onFinishListener;
    boolean finish;

    public boolean isFinish() {
        return finish;
    }

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    long remainTime = endTime - System.currentTimeMillis();
                    if (remainTime > 0) {
                        CountDownView.this.setText(getRemainText(remainTime));
                        handler.sendEmptyMessageDelayed(0, 1000);
                    } else {
                        finish = true;
                        CountDownView.this.setText(finishText);
                        if (onFinishListener != null) {
                            onFinishListener.onFinish();
                        }
                    }
                    break;
            }
        }
    };

    public void setRemainTextParser(ReaminTextParser remainTextParser) {
        this.remainTextParser = remainTextParser;
    }

    public long getEndTime() {
        return endTime;
    }

    /**
     * 由于ListView刷新列表时View会频繁刷新和重建，剩余时间难以保存和同步，这里改为View每次重建时设置截止时间
     *
     * @param endTime
     */
    public void setEndTime(long endTime) {
        this.endTime = endTime;
        long remainTime = endTime - System.currentTimeMillis();
        if (remainTime > 0) {
            CountDownView.this.setText(getRemainText(remainTime));
            handler.removeMessages(0);
            handler.sendEmptyMessage(0);
            finish = false;
        } else {
            finish = true;
            CountDownView.this.setText(finishText);
        }
    }

    public void setRemainTime(long remainTime) {
        setEndTime(System.currentTimeMillis() + remainTime);
    }

    public void setOnFinishListener(OnFinishListener onFinishListener) {
        this.onFinishListener = onFinishListener;
    }

    public CountDownView(Context context) {
        super(context);
        initView(context, null);
    }

    public CountDownView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {
        loadAttr(context, attrs);
    }

    /**
     * @param remainTime 单位毫秒
     */
    private String getRemainText(long remainTime) {
        StringBuffer sb = new StringBuffer();
        long minute = remainTime / 60000;
        //剩余时间小于1秒且大于0秒则按一秒算
        long second = (long) Math.ceil(remainTime % 60000 *1.0/ 1000);
        if (remainTextParser != null) {
            return remainTextParser.getRemainText(minute,second);
        }
        switch (textFormat) {
            case "mm:SS":
                sb.append(getTwoDigit(minute));
                sb.append(":");
                sb.append(getTwoDigit(second));
                break;
            case "mm分SS秒":
                sb.append(getTwoDigit(minute));
                sb.append("分");
                sb.append(getTwoDigit(second));
                sb.append("秒");
                break;
            default:
                sb.append(getTwoDigit(minute));
                sb.append(":");
                sb.append(getTwoDigit(second));
                break;
        }
        return sb.toString();
    }

    private String getTwoDigit(long l) {
        if (l < 10) {
            return "0" + l;
        } else {
            return "" + l;
        }
    }


    private void loadAttr(Context context, AttributeSet attrs) {
        if (attrs == null) {
            return;
        }
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CountDownView);
        int formatInt = a.getInt(R.styleable.CountDownView_CountDownView_format, 0);
        switch (formatInt) {
            case 0:
                textFormat = "mm:SS";
                break;
            case 1:
                textFormat = "mm分SS秒";
                break;
            default:
                break;
        }
        setText(finishText);
    }

    @Override
    //为了防止内存溢出，view detached的时候handler移除消息
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        handler.removeMessages(0);
    }
}
